#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""调试启动问题"""

import subprocess
import time
import sys
import os

print("=== 启动调试 ===")

# 1. 检查Python环境
print("\n1. Python环境检查:")
result = subprocess.run([sys.executable, "--version"], capture_output=True, text=True)
print(f"   Python版本: {result.stdout.strip()}")
print(f"   Python路径: {sys.executable}")

# 2. 检查依赖
print("\n2. 检查关键依赖:")
deps = ["flask", "selenium", "requests", "beautifulsoup4"]
for dep in deps:
    try:
        __import__(dep)
        print(f"   ✓ {dep} 已安装")
    except ImportError:
        print(f"   ✗ {dep} 未安装")

# 3. 尝试导入app.py
print("\n3. 尝试导入app.py:")
try:
    sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
    import app
    print("   ✓ app.py导入成功")
except Exception as e:
    print(f"   ✗ 导入失败: {e}")
    sys.exit(1)

# 4. 直接启动Flask应用
print("\n4. 尝试直接启动Flask应用:")
try:
    print("   启动中...")
    # 设置环境变量
    os.environ['FLASK_ENV'] = 'development'
    os.environ['FLASK_DEBUG'] = 'false'  # 关闭调试模式避免重载
    
    # 创建一个测试进程
    proc = subprocess.Popen(
        [sys.executable, "app.py"],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True
    )
    
    # 等待几秒看是否启动
    print("   等待服务启动...")
    time.sleep(5)
    
    # 检查进程是否还在运行
    if proc.poll() is None:
        print("   ✓ 进程正在运行")
        
        # 测试API
        try:
            import requests
            response = requests.get("http://localhost:5000/health", timeout=5)
            print(f"   ✓ API响应: {response.status_code}")
        except Exception as e:
            print(f"   ✗ API无响应: {e}")
        
        # 显示输出
        print("\n5. 进程输出:")
        stdout, stderr = proc.communicate(timeout=2)
        if stdout:
            print("   标准输出:")
            print(stdout)
        if stderr:
            print("   错误输出:")
            print(stderr)
        
        # 终止进程
        proc.terminate()
    else:
        # 进程已退出，获取输出
        stdout, stderr = proc.communicate()
        print(f"   ✗ 进程已退出，返回码: {proc.returncode}")
        print("\n   标准输出:")
        print(stdout)
        print("\n   错误输出:")
        print(stderr)
        
except Exception as e:
    print(f"   ✗ 启动失败: {e}")

# 6. 检查日志文件
print("\n6. 检查日志文件:")
log_files = ["live_monitor.log", "app.log", "logs/api.log"]
for log_file in log_files:
    if os.path.exists(log_file):
        print(f"\n   {log_file} 最后10行:")
        with open(log_file, 'r', encoding='utf-8') as f:
            lines = f.readlines()
            for line in lines[-10:]:
                print(f"     {line.strip()}")

print("\n=== 调试完成 ===")